package com.kunbo.controller.local;

import com.kunbo.entity.Event;
import com.kunbo.entity.Message;
import com.kunbo.entity.Page;
import com.kunbo.entity.User;
import com.kunbo.event.EventProducer;
import com.kunbo.service.MessageService;
import com.kunbo.service.UserService;
import com.kunbo.util.CommunityConstant;
import com.kunbo.util.HostHolder;
import com.kunbo.util.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @Autowired
    private EventProducer eventProducer;

    //私信列表
    @RequestMapping(value = "/vip/list",method = RequestMethod.GET)
    public String getLetterList(Model model, Page page){
        User user = hostHolder.getUser();
//        //分页信息
        page.setLimit(5);
        page.setPath("/vip/list");
        page.setRows(messageService.findConversationCount(user.getId()));
        //会话列表
        List<Message> conversationList = messageService.findConversations(
                user.getId(), page.getOffers(), page.getLimit());//查找有多少会话的最后一条并显示
        List<Map<String, Object>> conversations = new ArrayList<>();
        if(conversationList != null){
            for (Message message : conversationList) {
                Map<String, Object> map = new HashMap<>();
                map.put("conversation", message);//会话
//                System.out.println(message);
                map.put("letterCount", messageService.findLetterCount(message.getConversationId()));//私信数量
                map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));//未读消息数量
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();//得到目标id
                map.put("targetId", targetId);
                map.put("target", userService.findUserById(targetId));

                conversations.add(map);
            }
        }
        model.addAttribute("conversations", conversations);

        //查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        return "VIP/vip";
    }

    @RequestMapping(value = "/vip/vipdeail/{conversationId}", method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model){
        //分頁信息
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.findLetterCount(conversationId));

        List<Message> letterList = messageService.findLetters(conversationId, page.getOffers(), page.getLimit());
        List<Map<String, Object>> letters = new ArrayList<>();
        if(letterList != null){
            for(Message message : letterList){
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);

        //查詢私信目標人
        model.addAttribute("target", getLetterTarget(conversationId).getUsername());

        return "VIP/vipdetail";
    }

    @RequestMapping(value = "/vip/send", method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content){
        System.out.println(toName);
        System.out.println(content);
        User target = userService.findUserByName(toName);
        if(target == null){
            return JSON.getJSONString("1", "目标用户不存在");
        }

        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        if(message.getFromId() < message.getToId()){
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setStatus(0);
        message.setCreateTime(new Date());
        messageService.addMessage(message);

        //触发评论事件
        Event event = new Event()
                .setTopic(TOPIC_COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setData("postId", message.getConversationId());

        eventProducer.fireEvent(event);

        return JSON.getJSONString("0", "消息发送成功");
    }

    private User getLetterTarget(String conversationId){
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if(hostHolder.getUser().getId() == id0){
            return userService.findUserById(id1);
        }else {
            return userService.findUserById(id0);
        }
    }
}
